package com.example.shixi.service;

import com.example.shixi.domain.BlogArticle;
import com.example.shixi.domain.BlogArticleExample;
import com.example.shixi.mapper.BlogArticleMapper;
import com.example.shixi.pojo.UserPage;
import com.example.shixi.util.JSONResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ArticleService {
    @Resource
    private BlogArticleMapper blogArticleMapper;
    public JSONResult query(BlogArticle articleName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        BlogArticleExample blogArticleExample = new BlogArticleExample();
        BlogArticleExample.Criteria criteria = blogArticleExample.createCriteria();
        //BlogArticleExample blogArticleExampleAll = new BlogArticleExample();
        UserPage<BlogArticle> userPage= new UserPage<>();

        //List<BlogArticle> blogArticlesAll = blogArticleMapper.selectByExample(blogArticleExampleAll);
        if(!ObjectUtils.isEmpty(articleName)){
            criteria.andArticleNameLike("%"+articleName.getArticleName()+"%");
        }

        List<BlogArticle> blogArticles = blogArticleMapper.selectByExample(blogArticleExample);
        PageInfo<BlogArticle> pageInfo= new PageInfo<>(blogArticles);
        userPage.setList(blogArticles);
        userPage.setTotal(pageInfo.getTotal());
        userPage.setPageNum(pageNum);
        userPage.setPageSize(pageSize);
        return JSONResult.success(userPage);

    }

    public JSONResult add(BlogArticle ba) {
        ba.setArticleReadCount(0);//默认阅读量是0
        ba.setArticleStarNum(0);//默认点赞量是0
        ba.setArticleCommentNum(0);//默认评论量是0
        ba.setUpdateTime(new Date());
        blogArticleMapper.insertSelective(ba);
        return JSONResult.success("成功");
    }

    public JSONResult del(Long id) {
        blogArticleMapper.deleteByPrimaryKey(id);
        return JSONResult.success("成功");
    }

    public JSONResult update(BlogArticle ba) {
        blogArticleMapper.updateByPrimaryKeySelective(ba);
        return JSONResult.success("成功");
    }
}
